package dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
    static String url = null;
    static String username = null;
    static String password = null;

    protected Connection conn = null;
    protected PreparedStatement pstmt = null;
    protected ResultSet rs = null;


    static {
        init();
    }


    public static void init() {                           //获取连接并捕获异常
        try {
            Properties params = new Properties();
            String configFile = "database.properties";

            InputStream is = BaseDao.class.getClassLoader().getResourceAsStream(configFile);
            params.load(is);
            String driver = params.getProperty("driver");
            url = params.getProperty("url");
            username = params.getProperty("username");
            password = params.getProperty("password");
            Class.forName(driver);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }


    public void closeAll(Connection conn,Statement stmt,ResultSet rs) {
        try {
            if (null != rs) {
                rs.close();
            }
            if (null != stmt) {
                stmt.close();
            }
            if (null != conn) {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
